<template>
  <div>
    <div class=" text-lg">
      <i class="el-icon-folder" @click="openFileChoice()" />
      <i class="el-icon-link" @click="openLink()" />
    </div>
    <Tinymce ref="editor" v-model="contents.msg" :height="height" />
    <el-dialog
      :visible.sync="userFileVisible"
      top="15px"
    >
      <user-file :model="fileModel" @change="fileChoice" />
    </el-dialog>
    <el-dialog
      :visible.sync="linkVisible"
      top="15px"
    >
      <el-form
        ref="form"
        :model="link"
        label-width="80px"
      >
        <el-form-item :label="$t('text')">
          <el-input v-model="link.title" />
        </el-form-item>
        <el-form-item :label="$t('url')">
          <el-input v-model="link.url" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="linkVisible = false">{{ $t('cancel') }}</el-button>
        <el-button type="primary" @click="addLink">{{ $t('add') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import UserFile from '@/components/UserFile'
import { getFileType } from '@/util/common'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'UeditorFrom',
  components: {
    Tinymce,
    UserFile
  },
  props: {
    content: {
      type: String,
      default: ''
    },
    height: {
      type: String,
      default: '400'
    },
    value: {}
  },
  data() {
    return {
      contents: this.content,
      userFileVisible: false,
      linkVisible: false,
      fileModel: '',
      link: {}
    }
  },
  watch: {
    content: function(val) {
      this.contents = this.content
    },
    contents: function(val) {
      this.$emit('input', val)
    }
  },
  beforeMount() {
    // 接收 v-model 数据
    if (this.value) {
      this.contents = this.value
    }
  },
  methods: {
    openFileChoice() {
      this.fileModel = 'choice'
      this.showUserFile()
    },
    openLink() {
      this.link = {
        title: '',
        url: ''
      }
      this.linkVisible = true
    },
    addLink() {
      this.content = this.content + `<a href="${this.link.url}" >${this.link.title}</a>`
      this.linkVisible = false
    },
    showUserFile() {
      this.userFileVisible = true
    },
    fileChoice(filePath) {
      let content
      const type = getFileType(filePath)
      switch (type) {
        case 'mp4':
        case 'ogg':
        case 'webm':
          content = `
          <video width="100%" height="240" controls>
               <source src="${filePath}" type="video/${type}">
           </video>
          `
          break
        case 'jpg':
        case 'jpeg':
        case 'png':
          content = `<img width="100%" src="${filePath}" />`
          break
        default:
          content = `<a href="${filePath}" >${filePath}</a>`
      }
      this.content = this.content + content
      this.userFileVisible = false
    }
  }
}
</script>

